import {_decorator, Component, Node, Vec3, v3, find} from 'cc';

const {ccclass, property} = _decorator;

/**
 * 相机跟随
 */
@ccclass('FollowCameraController')
export class FollowCameraController extends Component {
    /**
     * 相机与玩家之间的偏移量
     */
    private offsetCamera: Vec3 = v3();

    start() {
        // 获取玩家的世界坐标
        let playerPos: Vec3 = find("player01").getWorldPosition();
        // 获取主相机的世界坐标
        let cameraPos: Vec3 = find("Main Camera").getWorldPosition();
        // 偏移量 = 相机坐标 - 玩家坐标
        Vec3.subtract(this.offsetCamera, cameraPos, playerPos);
    }

    update(deltaTime: number) {
        // 目标位置
        let targetCamera = v3();
        // 目标位置 = 玩家坐标 + 偏移量
        Vec3.add(targetCamera, find("player01").getWorldPosition(), this.offsetCamera);
        // 设置位置
        this.node.setWorldPosition(targetCamera);
    }
}

